<?php


namespace App\Customer\Controller;

use App\Customer\Model\CaseModel;
use App\Web\Model\Resume as ResumeModel;
use App\Customer\Model\ResumeRecommend as RecommendModel;
use App\Customer\Model\ResumeRecommendDetail as RRDetailModel;
use App\Facades\UrlCrypt;
use App\Service\Dict;
use App\Service\DictConstant;
use App\Service\ExternalAPI\VApi;
use App\Web\Model\Manager;
use EchoPHP\Http\Request;
use EchoPHP\Http\Response\JsonResponse;
use Exception;

class Resume extends Controller {

    /*
     * 获取简历列表数据
     */
    public function getRecommendList(Request $request) {

        $recommendId = $request->getParam('recommendid', 0);
        $pageNum = $request->getParam('pagenum/d', 1);
        $pageLimit = $request->getParam('pagelimit/d', 10);

        $subId = $request->getParam('subid/d', 0);
        $caseModel = new CaseModel();
        $subIds = $this->getSubIds();
        //判断用户是否和subid有关联
        if (empty($subId) || !$caseModel->checkSubIdByHrUid($subIds, $subId)) {
            return $this->json([
                'status' => false,
                'message' => 'subid出错！'
            ]);
        }
        $recommendModel = new RecommendModel();
        $token = $request->getParam('token', '');
        $tokenStatus = $recommendModel->checkToken($token,$subId,$recommendId);
        if(!$tokenStatus) {
            return $this->json([
                'status' => false,
                'message' => 'token出错！'
            ]);
        }


        //获取推荐的caseid
        $field = "caseid";
        $caseIds = $recommendModel->getCaseIdFromRecommend($recommendId, $field);

        if (!isset($caseIds["caseid"]) || $caseIds["caseid"] == '') {
            return $this->json(
                ['status' => false,
                    'message' => '无此数据',
                    'caselist' => [],
                ]
            );
        }

        $search = [
            'recommendid' => $recommendId,
            'caseid' => $caseIds,
            'status' => $request->getParam('status')
        ];

        $rRDetailModel = new RRDetailModel();
        $count = $rRDetailModel->getRecommendCount($search);
        if (empty($count) && $count !== 0) {
            return $this->json(
                [
                    'status' => false,
                    'message' => '无此数据',
                    'caseinfo' => [],
                ]
            );
        }

        $field = '';
        list($pageNum, $rowFrom, $rowTo) = $rRDetailModel->paginationParameters($pageNum, $pageLimit);
        $result = $rRDetailModel->getRecommendList($field, $search, $rowFrom, $rowTo);
        if (!$result) {
            return $this->json(
                ['status' => false,
                    'message' => '无此数据',
                    'caseinfo' => [],
                ]
            );
        }

        $caseIds = array_unique(array_column($result,'caseid'));
        $caseIds = implode(',',$caseIds);
        //获取职位信息
        $caseModel = new CaseModel();
        $field = ' SCase.casename,SCase.caseshowname,SCase.area,SCase.caseid ';
        $caseInfo = $caseModel->getCaseList($field, $caseIds);
        $attributes = [
            'area' => [DictConstant::DD_CITY_COUNTY, '']
        ];

        $dict = new Dict();
        $dict->rowTrans($caseInfo, $attributes, true, ',', ' ');
        $caseInfo = array_column($caseInfo,null,'caseid');
        $resumeID = [];
        foreach ($result as $key => $item) {
            $resumeID[] = $item['resumeid'];
        }

        $managerModel = new Manager();
        $resumeInfo = $managerModel->getManagerListByResumeId($resumeID);
        $resumeList = [];
        if (!empty($resumeInfo)) {
            foreach ($resumeInfo as $key => $item) {
                $resumeList[$item['resumeid']]['recentcompany'] = isset($item['company']) ? $item['company'] : ''; //之前公司
                $resumeList[$item['resumeid']]['recentduty'] = isset($item['position']) ? $item['position'] : '';   //之前职位
                $resumeList[$item['resumeid']]['age'] = isset($item['age']) ? $item['age'] : '';    //年龄
                $resumeList[$item['resumeid']]['cname'] = isset($item['cname']) ? $item['cname'] : '';  //姓名
                $resumeList[$item['resumeid']]['area'] = isset($item['area']) ? $item['area'] : '';   // 地区
                $resumeList[$item['resumeid']]['gender'] = isset($item['gender']) ? $item['gender'] : '';  // 性别
                $resumeList[$item['resumeid']]['recentworkindustry'] = isset($item['workindustry']) ? $item['workindustry'] : ''; // 行业
                $resumeList[$item['resumeid']]['degree'] = isset($item['degree']) ? $item['degree'] : '';   // 学历
                $resumeList[$item['resumeid']]['birthday'] = isset($item['birthday']) ? date("Y-m-d", strtotime($item['birthday'])) : ''; //出生年月
                $resumeList[$item['resumeid']]['expsalaryfrom'] = isset($item['expsalaryfrom']) ? $item['expsalaryfrom'] : ''; //期望工资
                $resumeList[$item['resumeid']]['expsalaryto'] = isset($item['expsalaryto']) ? $item['expsalaryto'] : ''; //期望工资
            }
        }
        unset($resumeInfo);

        $recommendList = [];
        $dictStatus = $rRDetailModel->RecommendStatus();

        $recommendModel = new RecommendModel();
        $recommendInfo = $recommendModel->getMyRecommend('recommender,extraparams', ['id' => $recommendId]);
        $recommender = '';
        $showFields = ['cname' => 1,'company' => 1];
        if (!empty($recommendInfo)) {
            $recommender = $recommendInfo[0]['recommender'] ?? '';
            $extraParams = json_decode($recommendInfo[0]['extraparams'] ?? '', true);
            $showFields = $extraParams['showFields'] ?? [];
        }

        foreach ($result as $key => $item) {
            $tmpObj = isset($resumeList[$item['resumeid']]) ? $resumeList[$item['resumeid']] : [];
            $tmpObj['id'] = $item['id'];
            $tmpObj['recommendid'] = $item['recommendid'];
            $tmpObj['subid'] = $item['subid'];
            $tmpObj['caseid'] = $item['caseid'];
            $tmpObj['caseinfo'] = isset($caseInfo[$item['caseid']]) ? $caseInfo[$item['caseid']] : [];
            $tmpObj['resumeid'] = $item['resumeid'];
            $tmpObj['recommendcreatedate'] = !empty($item['createdate']) ? date("Y-m-d H:i" , strtotime($item['createdate'])) : '';
            $tmpObj['recommendupdatedate'] = $item['status'] == '01' ? '' : date("Y-m-d H:i" , strtotime($item['updatedate']));
            $tmpObj['recommendstatus'] = $item['status'];
            $tmpObj['recommendmemo'] = $item['memo'];
            $tmpObj['recommendstatusname'] = isset($dictStatus[$item['status']]) ? $dictStatus[$item['status']] : '';
            $tmpObj['mailuserid'] = isset($item['creator']) ? $item['creator'] : '';
            $tmpObj['token'] = $token;
            $recommendList[] = $tmpObj;
        }
        unset($result);

        $resumeModel = new ResumeModel();

        //没有下载的简历，核心字段屏蔽
        if (!empty($recommendList)) {
            $alreadyDownList = [];
            if (!empty($recommender)) $alreadyDownList = $resumeModel->getDownloadResumeId($recommender, array_column($recommendList, 'resumeid'), true);
            $resumeModel->hideNotDownloadedFields($recommendList, $alreadyDownList);
        }
        $resumeModel->hideFields($recommendList, $showFields);
        $recommendModel = new RecommendModel();
        $recommendModel->setRecommendReadTime($recommendId);
        //设置首次查看时间

        return $this->json(
            ['status' => true,
                'message' => 'success',
                'totalCount' => $count,
                'resultList' => $recommendList
            ]
        );
    }

    /*
     * 设置推荐状态
     */
    public function setRecommendDetailStatus(Request $request) {
        $ids = $request->getPost('ids');
        $subId = $request->getParam('subid');
        $status = $request->getPost('status');
        $memo = $request->getPost('memo', '');
        $recommendId = $request->getParam('recommendid', 0);
        $token = $request->getParam('token');
        $recommendModel = new RecommendModel();
        $tokenStatus = $recommendModel->checkToken($token,$subId,$recommendId);
        //判断用户是否和subid有关联
        $caseModel = new CaseModel();
        $subIds = $this->getSubIds();
        if (empty($subId) || !$caseModel->checkSubIdByHrUid($subIds, $subId)) {
            return $this->json([
                'status' => false,
                'message' => 'subid出错！'
            ]);
        }
        if(!$tokenStatus) {
            return $this->json([
                'status' => false,
                'message' => 'token出错！'
            ]);
        }
        $rRDetailModel = new RRDetailModel();
        if (!empty($memo) && mb_strlen($memo) > 200) {
            return $this->json([
                'status' => false,
                'message' => '评语最多输入200字'
            ]);
        }
        $result = $rRDetailModel->setRecommendDetailStatus($subId, $ids, $status, $memo);
        return $this->json(
            [
                'status' => $result,
                'message' => $result ? '简历反馈保存成功' : '简历反馈保存失败'
            ]
        );
    }


    /*
     * 获取简历详情数据
     */
    public function resumeShow(Request $request) {
        $resumeIds = $request->getParam('resumeid', '');
        $channel = $request->getParam('channel', '');
        $token = $request->getParam('token', '');
        $subId = $request->getParam('subid', '');
        $recommendId = $request->getParam('recommendid', '');
        $resumeRecommendDetailId = $request->getParam('id', '');
        if (empty($resumeIds)) {
            $resultBody['status'] = false;
            $resultBody['message'] = '未查到对应记录';
            return $this->json($resultBody);
        }

        $resumeIds = explode(',', $resumeIds);
        if (count($resumeIds) != 1) {
            $resultBody['status'] = false;
            $resultBody['message'] = '未查到对应记录';
            return $this->json($resultBody);
        }

        if (empty($resumeIds[0])) {
            $resultBody['status'] = false;
            $resultBody['message'] = '未查到对应记录';
            return $this->json($resultBody);
        }

        $keyVerify = [];
        $keyVerify['recommendid'] = $recommendId;
        $keyVerify['subid'] = $subId;
        if (empty($token) || $token != UrlCrypt::generateToken($keyVerify)) {
            $resultBody['status'] = false;
            $resultBody['message'] = '未查到对应记录';
            return $this->json($resultBody);
        }

        $thisResumeId = $resumeIds[0];
        $resumeIds = [$thisResumeId];

        $resumeModel = new ResumeModel();

        $recommendModel = new RecommendModel();
        $recommendInfo = $recommendModel->getMyRecommend('recommender,extraparams', ['id' => $recommendId]);
        $recommender = '';
        $showFields = ['cname' => 1,'company' => 1];
        if (!empty($recommendInfo)) {
            $recommender = $recommendInfo[0]['recommender'] ?? '';
            $extraParams = json_decode($recommendInfo[0]['extraparams'] ?? '', true);
            $showFields = $extraParams['showFields'] ?? [];  //新版暂时隐藏关键字段 2020-6-29
        }

        $resumeModel->arrValueToKey($resumeIds);
        $resultBody['status'] = true;
        $resultBody['resumeList'] = $resumeModel->getResumeInfo($resumeIds, $recommender, $channel);

        if (!empty($resultBody['resumeList'])) {
            $resumeModel->hideFields($resultBody['resumeList'], $showFields);

            //简历反馈页 附加信息 其他栏目 暂不显示。
            $resultBody['resumeList'][$thisResumeId]['others'] = [];
            $resultBody['resumeList'][$thisResumeId]['hasothersinfo'] = 0;

            $rRDetailModel = new RRDetailModel();
            $resultDetail = $rRDetailModel->getRecommendOne('', $resumeRecommendDetailId, $thisResumeId);
            $resultBody['resumeList'][$thisResumeId]['recommendstatuscode'] = '';
            if ($resultDetail) {
                $resultBody['resumeList'][$thisResumeId]['recommendstatuscode'] = $resultDetail['status'];
            }
        }

        return $this->json($resultBody);
    }


    /**
     * 获取简历头像
     * @param Request $request
     * @return JsonResponse
     * @throws Exception
     */
    public function resumeAvatar(Request $request) {
        $resumeId = $request->getParam('resumeid', '');
        $accountId = $request->getParam('accountid', '');
        $platform = $request->getParam('platform', '');
        $gender = $request->getParam('gender', '');

        $fileContent = '';
        if ($platform == 'rpo' && $resumeId >= 2400000000) {
            //检测简历是否是RPO简历
            $resumeModel = new ResumeModel();
            $result = $resumeModel->getResumeBaseInfo($resumeId, 'headpath');
            if (!empty($result) && !empty($result['headpath'])) {
                $fileContent = @file_get_contents(FILESERVER . '/' . $result['headpath']);
            }
        } else if (!empty($resumeId) && !empty($accountId) && $resumeId < 2400000000) {
            $vapi = new VApi();
            $logo = $vapi->getResumeAvatar($accountId, $resumeId);
            if (!empty($logo) && strlen($logo) > 100) {
                $fileContent = base64_decode(preg_replace('/^\s*data:image\/(?:jpeg|jpg|png);base64,\s*(?=[A-Za-z0-9+\/])(?!\s)/', '', $logo, 1));
            }
        }

        header("Content-Type: application/octet-stream");
        //请求失败或者没有头像时使用默认头像
        if (empty($fileContent)) {
            if ($gender == '女' || strtolower($gender) == 'female') {
                $fileContent = @file_get_contents(ROOT_PATH . '/app/Command/ExportFile/resource/woman.png');
            } else {
                $fileContent = @file_get_contents(ROOT_PATH . '/app/Command/ExportFile/resource/man.png');
            }
        }

        echo $fileContent;
    }

    /**
     * 获取简历附件
     * @param Request $request
     * @return JsonResponse
     * @throws Exception
     */
    public function resumeAttachment(Request $request) {
        $vapi = new VApi();
        $resumeId = $request->getParam('resumeid', '');
        $accountId = $request->getParam('accountid', '');
        $attachId = $request->getParam('attachid', '');

        /*
        $resumeId = 301809654;
        $accountId = 51911892;
        $attachId = 8244043;
        */
        if (empty($resumeId) || empty($accountId) || empty($attachId)) {
            exit();
        }

        $attInfo = $vapi->getResumeAttachment($accountId, $resumeId, $attachId);
        $fileContent = $attInfo[0]["attachfile"];
        $fileContent = base64_decode(preg_replace('/data:image\/[jpeg|jpg|png]+;base64,/', '', $fileContent));
        header("Content-Type: application/octet-stream");
        echo $fileContent;
    }
}